/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tallerfinal.util.distributions;

import tallerfinal.util.distributions.factory.GeneratorsFactory;
import tallerfinal.util.enums.DistributionsName;

/**
 *
 * @author ricardo
 */
public class BinomialGenerator extends Generator<Integer> {

    static {
        GeneratorsFactory.getInstance().registerProduct(DistributionsName.BINOMIAL, BinomialGenerator.class);
    }
    private double p;
    private int n;

    public BinomialGenerator(double p, int n) {
        this.p = p;
        this.n = n;
    }

    @Override
    public Integer generate() {
        int x = 0;
        double px = Math.pow(1 - p, n);
        double Fx = px;
        double u = generator.nextDouble();
        while (u > Fx) {
            x++;
            px = px * (p / (1 - p) * (n - (x - 1)) / x);
            Fx = Fx + px;
        }
        return x;
    }
}
